package com.guarantee.server.common.core.text.handle;

import com.guarantee.server.common.exception.BaseBusiException;
import com.guarantee.server.common.replay.ReplyCode;
import com.guarantee.server.common.response.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;


/**
 * @author qwer
 * @date 2018-11-26
 * @description
 */
@Slf4j
@ControllerAdvice
public class ExceptionHandle {


    //@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RestResponse handle(Exception e) {
        e.printStackTrace();
        if (e instanceof BaseBusiException) {
            return new RestResponse<>(ReplyCode.SYS.FAIL, e.getMessage());
        } else if (e instanceof IllegalArgumentException) {
            return new RestResponse(ReplyCode.SYS.FAIL, e.getMessage());
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            return new RestResponse(ReplyCode.SYS.FAIL, "请求类型不支持");
        } else if (e instanceof DuplicateKeyException) {
            return new RestResponse(ReplyCode.SYS.FAIL, "数据已存在");
        } else if (e instanceof MethodArgumentTypeMismatchException) {
            return new RestResponse(ReplyCode.SYS.FAIL, "参数类型赋值失败");
        } else if (e instanceof MissingServletRequestParameterException) {
            return new RestResponse(ReplyCode.SYS.FAIL, "获取参数失败");
        }else if (e instanceof BindException) {
            BindingResult bindingResult = ((BindException)e).getBindingResult();
            String message = null;
            if (bindingResult.hasErrors()) {
                FieldError fieldError = bindingResult.getFieldError();
                if (fieldError != null) {
                    message = fieldError.getField()+fieldError.getDefaultMessage();
                }
            }
            return new RestResponse(ReplyCode.SYS.FAIL,message);
        } else {
            return new RestResponse<>(ReplyCode.SYS.FAIL, e.getMessage());
        }
    }



}
